program mynormal7, sortpreserve
	version 8.1
	if replay() {
		if (`"`e(cmd)'"' != "mynormal7") error 301
		Replay `0'
	}
	else	Estimate `0'
end

program Estimate, eclass
	syntax varlist [if] [in]		///
		[fweight pweight] [,		///
		noLOg				/// -ml model- options
		noCONStant			///
		Robust				///
		CLuster(varname)		///
		HETero(varlist)			///
		noLRTEST			///
		Level(integer `c(level)')	/// -Replay- option
		*				/// -mlopts- options
	]

	// check syntax
	mlopts mlopts, `options'
	local cns `s(constraints)'
	gettoken lhs rhs : varlist
	if "`cluster'" != "" {
		local clopt cluster(`cluster')
	}
	if "`weight'" != "" {
		tempvar wvar
		quietly gen double `wvar' `exp'
		local wgt "[`weight'=`wvar']"
		// for initial value calculations
		local awgt "[aw=`wvar']"		// <-NEW
	}
	if `"`robust'`cluster'`cns'"' != ""	///
	| "`weight'" == "pweight" {
		local lrtest nolrtest
	}
	if "`log'" != "" {
		local qui quietly
	}
	// mark the estimation sample
	marksample touse
	markout `touse' `wvar'
	markout `touse' `cluster', strok

	if "`constant'" == "" {
		// initial values			-- NEW block
		quietly sum `lhs' `awgt' if `touse'
		local mean = r(mean)
		local lnsd = ln(r(sd))+ln((r(N)-1)/r(N))/2
		local initopt init(/mu=`mean' /lnsigma=`lnsd') search(off)

		`qui' di as txt _n "Fitting constant-only model:"
		ml model lf mynormal_lf				///
			(mu: `lhs' = )				///
			(lnsigma: `hetero')			///
			`wgt' if `touse',			///
			`log'					///
			`mlopts'				///
			`initopt'				/// <- NEW
			nocnsnotes				///
			missing					///
			maximize
		if "`lrtest'" == "" {
			local contin continue search(off)
		}
		else {
			tempname b0
			mat `b0' = e(b)
			local contin init(`b0') search(off)
		}
		`qui' di as txt _n "Fitting full model:"
	}

	// fit the full model
	ml model d2 mynormal_d2				///
		(mu: `lhs' = `rhs', `constant')		///
		(lnsigma: `hetero')			///
		`wgt' if `touse',			///
		`log'					///
		`mlopts'				///
		`robust'				///
		`clopt'					///
		`contin'				///
		missing					///
		maximize

	ereturn local cmd mynormal7

	Replay , level(`level')
end

program Replay
	syntax [, Level(integer `c(level)') ]
	ml display , level(`level')
end
